import { confirmOption } from '@/config/global.config';
import { notification, Modal } from 'ant-design-vue';
import { isObject } from '@/utils/validate';
import router from '@/router';

/**
 * @description: 系统提示
 * @param {*} type 类型： success info warning error
 * @param {*} msg 提示内容
 * @return {*}
 */
function openNotification(type, msg) {
  notification[type]({
    message: '系统提示',
    description: msg,
  });
}
export function toast(msg) {
  openNotification('success', msg);
}
toast.fail = (msg) => {
  return openNotification('error', msg);
};

/**
 * @description 确认弹窗
 * @param {Object/String} content 弹窗配置/弹窗内容
 * @param {Function} callBack 确认按钮的回调函数
 * @param {Function} cancelCallBack 取消按钮的回调函数
 */
export function ask(content) {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: '系统提示',
      ...getModalConfirmConfig(content),
      onOk() {
        resolve();
      },
      onCancel() {
        reject();
      },
    });
  });
}

ask.warn = (content) => {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: '系统提示',
      okType: 'danger',
      ...getModalConfirmConfig(content),
      onOk() {
        resolve();
      },
      onCancel() {
        reject();
      },
    });
  });
};

/**
 * @description 确认表单弹窗
 * @param {*} vm this
 * @param {*} fn 校验函数
 * @param {*} tip 文本
 */
ask.leave = (vm, fn = () => false, tip = '当前页面数据未保存，确认离开？') => {
  let isLeaving = false; // 是否正在离开页面

  // 监听组件更新事件，注册window.onbeforeunload事件
  vm.$on('hook:updated', () => {
    window.onbeforeunload = (event) => {
      if (isLeaving || !fn(vm)) return;
      event.preventDefault();
      event.returnValue = tip;
      return tip;
    };
  });

  // 添加全局的beforeEach导航守卫
  const beforeEachHandler = (to, from, next) => {
    if (isLeaving || !fn(vm)) {
      next();
    } else {
      ask
        .warn(tip)
        .then(() => {
          isLeaving = true;
          next();
        })
        .catch(() => {
          isLeaving = false;
          next(false);
        });
    }
  };
  router.beforeEach(beforeEachHandler);

  // 监听组件销毁事件，移除window.onbeforeunload事件和导航守卫
  vm.$on('hook:beforeDestroy', () => {
    window.onbeforeunload = null;
    router.beforeHooks.splice(router.beforeHooks.indexOf(beforeEachHandler), 1);
  });

  // 添加全局的afterEach导航守卫
  const afterEachHandler = () => {
    isLeaving = false;
  };
  router.afterEach(afterEachHandler);

  // 在组件销毁时移除全局的afterEach导航守卫
  vm.$on('hook:beforeDestroy', () => {
    router.afterHooks.splice(router.afterHooks.indexOf(afterEachHandler), 1);
  });
};

function getModalConfirmConfig(option) {
  let config = { ...confirmOption };
  if (isObject(option)) {
    config = { ...config, ...option };
  } else {
    config.content = option;
  }
  return config;
}
